const app = getApp();
import http from '../../utils/request.js'
import api from '../../utils/api.js'
let util = require("../../utils/util.js")
Page({

  /**
   * 页面的初始数据
   */
  data: {
    matchDict: {},
    dates: [],
    current: 1,
    isEnd: false,
    temp: []
  },
  onPullDownRefresh() {
    this.init()
    this.getList(1).then(list => {
      this.appendList(list)
      wx.stopPullDownRefresh()
      wx.hideNavigationBarLoading()
      this.onReachBottom()
    })
  },
  onReachBottom() {
    if (this.data.temp && this.data.temp.length) {
      this.appendList(this.data.temp)
      this.setData({
        temp: []
      })
    }
    if (this.data.isEnd) {
      return
    }
    let current = this.data.current
    current++
    this.setData({
      current
    })
    this.getList(current).then(list => {
      this.setData({
        temp: list
      })
    })
  },
  init() {
    this.setData({
      matchDict: {},
      dates: [],
      current: 1,
      isEnd: false,
      temp: []
    })
  },
  onLoad: function (options) {
    this.init()
    this.getList(1).then(list => {
      this.appendList(list)
      this.onReachBottom()
    })
  },
  showMatch() {

  },
  getList(page) {
    return new Promise((resolve, reject) => {
      http.get(api.matchDetail + "?current=" + page)
        .then(result => {
          let data = result.data.data;
          if (data.pages === page) {
            this.setData({
              isEnd: true
            })
          }
          let list = data.records;
          resolve(list)
        }).catch(e => {
          reject(e)
        });
    })
  },
  appendList(list) {
    let matchDict = this.data.matchDict;
    let dates = this.data.dates;
    for (let match of list) {
      let date = util.formatTime(new Date(match.endTime), 'yyyy-MM-dd');
      let time = util.formatTime(new Date(match.endTime), 'HH:mm');
      match.endTime = time;
      let matches
      if (!matchDict.hasOwnProperty(date)) {
        matches = [];
        matchDict[date] = matches;
        dates.push(new Date(date));
      } else {
        matches = matchDict[date];
      }
      matches.push(match);
    }
    let temp = [];
    for (let date of dates) {
      temp.push(util.formatTime(new Date(date), 'yyyy-MM-dd'));
    }
    temp.sort().reverse()
    this.setData({
      matchDict,
      dates: temp
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})